//
//  WatchMainDetailViewController.m
//  leo
//
//  Created by RyanLin on 11/8/15.
//  Copyright © 2015 mdx. All rights reserved.
//

#import "WatchMainDetailViewController.h"
#import "WatchQRCodeViewController.h"
#import <objc/runtime.h>
#import "AppDelegate.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "User.h"
#import "BindViewController.h"
@interface WatchMainDetailViewController ()


@property (nonatomic,strong) SyncManager *syncManager;
@property (nonatomic,strong) DataManager *dataManager;
@property (nonatomic,strong) Watch *selectWatch;
@property (nonatomic) BOOL isCkeckVersion;
@end



@implementation WatchMainDetailViewController
@synthesize syncManager;
@synthesize dataManager;
@synthesize selectWatch;
@synthesize QRButton;
@synthesize versionView;
@synthesize imeiLabel;
@synthesize isCkeckVersion;
-(void)dealloc
{
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.selectWatch=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"手表信息";
    [self initButton];
    [self initData];
    // Do any additional setup after loading the view from its nib.
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL&&mydelegate.isAdmin==NO)
    {
        self.versionNext.hidden=YES;
    }
    else
    {
        self.versionNext.hidden=NO;
        UITapGestureRecognizer *tapReconizerToGender = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(versionAction)];
        [versionView addGestureRecognizer:tapReconizerToGender];
        
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,getManagerPhotos,queue is null",DATAMANAGER_TAG);
        return;
    }
    if(selectWatch!=NULL)
    {
        if(selectWatch.is_latest==1)//有最新版本
        {
            self.nLab.hidden=NO;
        }
        else
        {
            self.nLab.hidden=YES;
        }
        if(selectWatch.version!=NULL&&![selectWatch.version isEqualToString:@"(null)"]&&![selectWatch.version isEqualToString:@""])
        {
            self.versionLab.text=[NSString stringWithFormat:@"当前版本%@",selectWatch.version];
        }
    }
}

-(void)initData
{
    isCkeckVersion=NO;
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    dataManager=[[DataManager alloc] init];
    if(dataManager==NULL)
        return;
    syncManager=[[SyncManager alloc] init];
    if(syncManager==NULL)
        return;
    selectWatch=[self.dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
        return;
    imeiLabel.text=selectWatch.imei;
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
    //[self dismissViewControllerAnimated:YES completion:nil];
}

-(void)initButton
{
    [QRButton addTarget:self action:@selector(pushQRCode) forControlEvents:UIControlEventTouchDown];
    UITapGestureRecognizer *tapReconizerToGender = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pushQRCode)];
    [self.QRnext addGestureRecognizer:tapReconizerToGender];
}
-(void)pushQRCode
{
    WatchQRCodeViewController *watchQRViewController=[[WatchQRCodeViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:watchQRViewController animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
-(void)versionAction
{
    if(selectWatch==NULL)
        return;
    if(!isCkeckVersion)
    {
        isCkeckVersion=YES;
        [syncManager deviceUpgrade:selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                Version *version=[retValue valueForKey:@"version"];
                if(version==NULL)
                    return;
                [self.dataManager updateWatchVersion:version];
                self.nLab.hidden=NO;
                NSString *title=[NSString stringWithFormat:@"检测到手表%@有新版本%@,版本大小为%.2fMB,是否现在升级？",selectWatch.nickname,version.fwVer,version.fileSize/(1024*1024)];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:title
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"确定",nil];
                objc_setAssociatedObject(alert, @"watch", version, OBJC_ASSOCIATION_RETAIN);
                [alert show];
                alert=nil;

            }
            else
            {
                [Tooler showHttpToast:result description:description msg:@"手表版本获取失败" parentView:self.navigationController.view  showPosition:TOAST_SHOW_END hideAfterDelay:1];

            }
            isCkeckVersion=NO;
        }];
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==1)
    {
        Version *watchVersion=objc_getAssociatedObject(alertView, @"watch");
        if(watchVersion!=NULL)
        {
            [self.syncManager sendCommand:watchVersion.deviceUid type:FIRMWARE_UPDATE  watchParams:NULL completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    [LeoMsg showMsg:@"成功向手表发送升级指令"];
                    [self.dataManager updateVersionState:watchVersion.deviceUid];
                }
                else
                {
                    [Tooler showHttpMsg:result description:description msg:@"手表升级失败"];
                }
            }];
            return;
        }
        NSString *unbind=objc_getAssociatedObject(alertView, @"unbind");
        if(unbind!=NULL&&[unbind isEqualToString:@"1"])
        {
            self.unbindBtn.enabled=NO;
            [syncManager unbindDevice:selectWatch completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                if(result==SUCESS)
                {
                    //[LeoMsg showToastMsg:@"解除绑定成功" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];

                    User *user=[User sharedSingleton];
                    if(user==NULL||user.uid==NULL)
                        return ;
                    NSArray *watchLists=[dataManager getWatchList:user.uid];
                    if(watchLists==NULL||[watchLists count]==0)
                    {
                        BindViewController *bindView=[[BindViewController alloc] init];
                        bindView.type=1;
                        UINavigationController *bindNav=[[UINavigationController alloc] initWithRootViewController:bindView];
                        AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                        if(mydelegate!=NULL)
                            [mydelegate setNavProperty:bindNav];
                        self.view.window.rootViewController=bindNav;
                        bindView=NULL;
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        
                    }
                    else
                    {
                        User *user=[User sharedSingleton];
                        if(user!=NULL&&user.uid!=NULL)
                        {
                            self.selectWatch=[self.dataManager getActiveWatch:user.uid];
                            if(self.selectWatch!=NULL)
                            {
                                [self.dataManager updateWatchState:self.selectWatch.deviceUid];
                                AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
                                if(mydelegate!=NULL)
                                {
                                    if(self.selectWatch.role==ADMIN)
                                        mydelegate.isAdmin=YES;
                                    else
                                        mydelegate.isAdmin=NO;
                                }
                                    
                            }
                        }

                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }
                    //发送解绑通知
                    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    if(queue==NULL)
                    {
                        NSLog(@"%@,getTaskPic,queue is null",DATAMANAGER_TAG);
                        return;
                    }
                    dispatch_async(queue, ^{
                        [[NSNotificationCenter defaultCenter] postNotificationName:UNBINDDEVICE object:nil  userInfo:nil];
                        
                    });
                    [LeoMsg showMsg:@"解除绑定成功"];
                    
                }
                else
                {
                    [Tooler showHttpToast:result description:description msg:@"解除绑定失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_MID hideAfterDelay:1];
                    self.unbindBtn.enabled=YES;

                }
            }];

        }
    }
}
- (IBAction)unbind:(id)sender {
    if(selectWatch==NULL)
        return;
    NSString *title=@"解除绑定后您将无法查看手表的状态，您确定要解除绑定？";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:title
                                                   delegate:self
                                          cancelButtonTitle:@"否"
                                          otherButtonTitles:@"是",nil];
    objc_setAssociatedObject(alert, @"unbind", @"1", OBJC_ASSOCIATION_RETAIN);
    [alert show];
    alert=nil;
}

@end
